﻿using Struct;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using HookHandle = FastCopyWin.Win32Api.HookHandle;

namespace FastCopyWin
{
    internal class MouseUtils
    {
        private const int WH_MOUSE_LL = 14;

        // 设置为静态变量防止被回收而导致 Api 函数异常
        private static readonly HookHandle mouseHookHandle = new(GetHookProc);
        private static IntPtr hookWindowPtr = IntPtr.Zero;
        private static int hHookValue = 0;

        private static readonly List<KeyAction> keyActionList = new();

        /// <summary>
        /// 添加鼠标按键的回调事件
        /// </summary>
        /// <param name="key">鼠标键</param>
        /// <param name="action">回调动作</param>
        public static void AddMouseAction(KeyEnum key, Action action)
        {
            keyActionList.Add(new KeyAction(key, action));
            if (hHookValue == 0)
            {
                hookWindowPtr = Win32Api.GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName);
                hHookValue = Win32Api.SetWindowsHookEx(
                    WH_MOUSE_LL,
                    mouseHookHandle,
                    hookWindowPtr,
                    0);
                Debug.WriteLine("鼠标监听挂载成功！" + hHookValue);
            }
        }
        private static int GetHookProc(int nCode, int wParam, IntPtr lParam)
        {
            if (nCode >= 0)
            { 
                foreach (KeyAction keyAction in keyActionList)
                {
                    if ((int)keyAction.key == wParam)
                    {
                        keyAction.action();
                    }
                }
            }
            return Win32Api.CallNextHookEx(hHookValue, nCode, wParam, lParam);
        }

        public static POINT GetCursorPosition()
        {
            Win32Api.GetCursorPos(out POINT point);
            return point;
        }

        public enum KeyEnum 
        {
            // 鼠标左键抬起
            LEFT_KEY = 0x0202
        }

        private class KeyAction
        {
            public KeyEnum key;
            public Action action;

            public KeyAction(KeyEnum key, Action action)
            {
                this.key = key;
                this.action = action;
            }
        }
    }
}
